<template>
  <div class="personnel-management">
    <!-- 搜索筛选区域 -->
    <div class="search-filters">
      <div class="filter-row">
        <!-- 协议编码搜索 -->
        <div>
          <span class="search-item">协议编码</span>
          <input
              v-model="searchForm.contractNo"
              type="text"
              placeholder="请输入协议编码"
              class="input-field"
          />
        </div>

        <!-- 户主姓名搜索 -->
        <div>
          <span class="search-item">户主姓名</span>
          <input
              v-model="searchForm.ownerName"
              type="text"
              placeholder="请输入户主姓名"
              class="input-field"
          />
        </div>

        <!-- 房屋编码搜索 -->
        <div>
          <span class="search-item">房屋编码</span>
          <input
              v-model="searchForm.houseCode"
              type="text"
              placeholder="请输入房屋编码"
              class="input-field"
          />
        </div>

        <!-- 联系电话搜索 -->
        <div>
          <span class="search-item">联系电话</span>
          <input
              v-model="searchForm.phone"
              type="text"
              placeholder="请输入联系电话"
              class="input-field"
          />
        </div>

        <!-- 合同到期日期搜索 -->
        <div>
          <span class="search-item">合同到期日期</span>
          <select v-model="searchForm.expiryOption" class="select-field">
            <option value="">请选择</option>
            <option value="custom">自定义日期</option>
            <option value="3months">三个月内到期</option>
            <option value="1month">一个月内到期</option>
            <option value="7days">七天内到期</option>
          </select>
        </div>

        <!-- 自定义日期输入框 -->
        <div v-if="searchForm.expiryOption === 'custom'">
          <span class="search-item">到期日期</span>
          <input
              v-model="searchForm.endDate"
              type="date"
              class="input-field"
          />
        </div>

        <div>
          <span class="search-item">合同状态</span>
          <select v-model="searchForm.contractStatus" class="select-field">
            <option value="">全部</option>
            <option :value="0">待生效</option>
            <option :value="1">生效</option>
            <option :value="2">过期</option>
            <option :value="3">终止</option>
          </select>
        </div>

        <button @click="handleSearch" class="btn-primary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPnga03cd43e27317f20428660e14317e35a64a3d907d88f824770f063b2f9fd5f10" alt="搜索" class="btn-icon" />
          搜索
        </button>
        <button @click="handleReset" class="btn-secondary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngd1ee69767e02bb56b7c745624d059b292108792e966600668227ff5d22467bbe" alt="重置" class="btn-icon" />
          重置
        </button>
      </div>
    </div>

    <!-- 分割线 -->
    <div class="divider"></div>

    <!-- 操作按钮组 -->
    <div class="operation-buttons">
      <button
          @click="handleAdd"
          :class="['btn-add', { 'btn-selected': operationMode === 'add' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngf1cdfd3741aaeaf19e733deebf065b44a820a4e6e4d83792de3c6e699c670645" alt="新增" class="btn-icon" />
        新增
      </button>

      <button
          @click="handleModeChange('edit')"
          :class="['btn-add', { 'btn-selected': operationMode === 'edit' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="修改" class="btn-icon" />
        修改
      </button>

      <button
          @click="handleModeChange('delete')"
          :class="['btn-add', { 'btn-selected': operationMode === 'delete' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" class="btn-icon" />
        删除
      </button>

      <!-- 批量删除按钮 -->
      <button
          v-if="operationMode === 'delete' && selectedContracts.length > 0"
          @click="handleBatchDelete"
          class="btn-batch-delete"
      >
        批量删除 ({{ selectedContracts.length }})
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr class="table-header">
          <!-- 删除模式下显示全选框 -->
          <th v-if="operationMode === 'delete'">
            <input
                type="checkbox"
                @change="handleSelectAll"
                :checked="isAllSelected"
                class="checkbox"
            />
          </th>
          <th>序号</th>
          <th>协议编码</th>
          <th>户主姓名</th>
          <th>联系电话</th>
          <th>房屋编码</th>
          <th>合同期限</th>
          <th>合同生效日期</th>
          <th>合同到期日期</th>
          <th>合同状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(contract, index) in paginatedContracts" :key="contract.contract_id" class="table-row">
          <!-- 删除模式下显示复选框 -->
          <td v-if="operationMode === 'delete'">
            <input
                type="checkbox"
                :value="contract.contract_id"
                v-model="selectedContracts"
                class="checkbox"
            />
          </td>
          <td>{{ (pagination.currentPage - 1) * pagination.pageSize + index + 1 }}</td>
          <td>{{ contract.contract_code }}</td>
          <td>{{ contract.tenant_name }}</td>
          <td>{{ contract.tenant_phone }}</td>
          <td>{{ contract.house_code }}</td>
          <td>{{ formatContractTerm(contract.contract_term) }}</td>
          <td>{{ formatDate(contract.effective_date) }}</td>
          <td>{{ formatDate(contract.expiry_date) }}</td>
          <td>
            <div :class="['status-badge', formatContractStatus(contract.contract_status).class]">
              {{ formatContractStatus(contract.contract_status).text }}
            </div>
          </td>
          <td class="action-buttons">
            <!-- 查看按钮 - 始终显示 -->
            <button @click="handleView(contract)" class="action-btn" title="查看详情">
              <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="查看" />
            </button>

            <!-- 编辑按钮 - 修改模式下显示 -->
            <button v-if="operationMode === 'edit'" @click="handleEdit(contract)" class="action-btn" title="编辑">
              <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="编辑" />
            </button>

            <!-- 删除按钮 - 删除模式下显示 -->
            <button v-if="operationMode === 'delete'" @click="handleSingleDelete(contract)" class="action-btn" title="删除">
              <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" />
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <span class="pagination-info">共 {{ pagination.totalPages }} 页</span>
      <button @click="goToPrevPage" :disabled="pagination.currentPage === 1" class="pagination-btn">上一页</button>
      <button
          v-for="page in visiblePages"
          :key="page"
          @click="goToPage(page)"
          :class="['pagination-btn', { 'active': page === pagination.currentPage }]"
      >
        {{ page }}
      </button>
      <button @click="goToNextPage" :disabled="pagination.currentPage === pagination.totalPages" class="pagination-btn">下一页</button>
      <span class="pagination-goto">前往</span>
      <input v-model.number="gotoPage" @keyup.enter="handleGotoPage" class="goto-input" />
      <span>页</span>
    </div>

    <!-- 新增/编辑/查看弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <div class="form-item">
              <label>协议编码</label>
              <input v-model="currentContract.contract_code" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>户主姓名</label>
              <input v-model="currentContract.tenant_name" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>联系电话</label>
              <input v-model="currentContract.tenant_phone" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>房屋编码</label>
              <input v-model="currentContract.house_code" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>合同期限</label>
              <input v-model="currentContract.contract_term" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>合同生效日期</label>
              <input v-model="currentContract.effective_date" type="date" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>合同到期日期</label>
              <input v-model="currentContract.expiry_date" type="date" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>合同状态</label>
              <select v-model="currentContract.contract_status" :disabled="modalType === 'view'" class="form-input">
                <option :value="1">生效</option>
                <option :value="0">终止</option>
              </select>
            </div>

            <!-- 新增/编辑时显示房屋详情信息 -->
            <template v-if="modalType !== 'view'">
              <div class="form-item">
                <label>租金</label>
                <input v-model="currentContract.rent" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item">
                <label>押金</label>
                <input v-model="currentContract.deposit" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item">
                <label>缴费到期日</label>
                <input v-model="currentContract.payment_due_date" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item">
                <label>续费周期</label>
                <input v-model="currentContract.payment_cycle" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item">
                <label>用水初始数据(吨)</label>
                <input v-model="currentContract.initial_water_meter" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item">
                <label>用电初始数据(度)</label>
                <input v-model="currentContract.initial_electricity_meter" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item">
                <label>煤气初始数据(m³)</label>
                <input v-model="currentContract.initial_gas_meter" :disabled="modalType === 'view'" class="form-input" />
              </div>
              <div class="form-item full-width">
                <label>备注</label>
                <textarea v-model="currentContract.remark" :disabled="modalType === 'view'" class="form-textarea"></textarea>
              </div>

              <!-- 合同扫描件上传 -->
              <div class="form-item full-width">
                <label>合同扫描文件</label>
                <div class="file-upload-area" @click="triggerFileInput" v-if="!currentContract.contract_scanner_url && modalType !== 'view'">
                  <div class="upload-placeholder">
                    <span>点击上传文件或拖拽文件到此处</span>
                  </div>
                  <input
                    ref="fileInput"
                    type="file"
                    @change="handleFileUpload"
                    accept=".pdf,.jpg,.jpeg,.png,.gif"
                    class="file-input"
                  />
                </div>
                <div v-else-if="currentContract.contract_scanner_url && modalType !== 'view'" class="file-preview-container">
                  <div class="uploaded-file-info">
                    <span>{{ getFileName(currentContract.contract_scanner_url) }}</span>
                    <button @click="removeFile" class="remove-file-btn">×</button>
                  </div>
                </div>
                <div v-else-if="modalType === 'view'" class="file-preview">
                  <div v-if="currentContract.contract_scanner_url" class="file-container">
                    <img
                      v-if="isImageFile(currentContract.contract_scanner_url)"
                      :src="currentContract.contract_scanner_url"
                      alt="合同扫描文件"
                      class="contract-file-preview"
                    />
                    <iframe
                      v-else-if="isPdfFile(currentContract.contract_scanner_url)"
                      :src="currentContract.contract_scanner_url"
                      class="contract-file-preview"
                    ></iframe>
                    <div v-else class="file-icon">
                      <span>📄</span>
                      <p>{{ getFileExtension(currentContract.contract_scanner_url) }} 文件</p>
                    </div>
                  </div>
                  <div v-else class="no-file">暂无文件</div>
                  <button
                    v-if="currentContract.contract_scanner_url"
                    @click="downloadFile(currentContract.contract_scanner_url)"
                    class="btn-download"
                  >
                    下载文件
                  </button>
                </div>
              </div>
            </template>

            <!-- 查看详情时显示额外信息 -->
            <template v-else>
              <div class="form-item full-width">
                <label>合同扫描文件</label>
                <div class="file-preview">
                  <div v-if="currentContract.contract_scanner_url" class="file-container">
                    <img
                      v-if="isImageFile(currentContract.contract_scanner_url)"
                      :src="currentContract.contract_scanner_url"
                      alt="合同扫描文件"
                      class="contract-file-preview"
                    />
                    <iframe
                      v-else-if="isPdfFile(currentContract.contract_scanner_url)"
                      :src="currentContract.contract_scanner_url"
                      class="contract-file-preview"
                    ></iframe>
                    <div v-else class="file-icon">
                      <span>📄</span>
                      <p>{{ getFileExtension(currentContract.contract_scanner_url) }} 文件</p>
                    </div>
                  </div>
                  <div v-else class="no-file">暂无文件</div>
                  <button
                    v-if="currentContract.contract_scanner_url"
                    @click="downloadFile(currentContract.contract_scanner_url)"
                    class="btn-download"
                  >
                    下载文件
                  </button>
                </div>
              </div>

              <div class="form-item">
                <label>创建人</label>
                <input v-model="currentContract.create_by" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>创建时间</label>
                <input v-model="currentContract.create_time" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>更新人</label>
                <input v-model="currentContract.update_by" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>更新时间</label>
                <input v-model="currentContract.update_time" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>租金</label>
                <input v-model="currentContract.rent" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>押金</label>
                <input v-model="currentContract.deposit" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>缴费到期日</label>
                <input v-model="currentContract.payment_due_date" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>续费周期</label>
                <input v-model="currentContract.payment_cycle" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>用水初始数据(吨)</label>
                <input v-model="currentContract.initial_water_meter" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>用电初始数据(度)</label>
                <input v-model="currentContract.initial_electricity_meter" disabled class="form-input" />
              </div>
              <div class="form-item">
                <label>煤气初始数据(m³)</label>
                <input v-model="currentContract.initial_gas_meter" disabled class="form-input" />
              </div>
              <div class="form-item full-width">
                <label>备注</label>
                <textarea v-model="currentContract.remark" disabled class="form-textarea"></textarea>
              </div>
            </template>
          </div>
        </div>
        <div v-if="modalType !== 'view'" class="modal-footer">
          <button @click="closeModal" class="btn-cancel">取消</button>
          <button @click="handleSave" class="btn-save">保存</button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="cancelDelete">
      <div class="modal-content delete-confirm-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="cancelDelete" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <p v-if="deleteType === 'single'">确定要删除合同 "{{ deleteTarget.contract_code }}" 吗？</p>
          <p v-else>确定要删除选中的 {{ selectedContracts.length }} 个合同吗？</p>
        </div>
        <div class="modal-footer">
          <button @click="cancelDelete" class="btn-cancel">取消</button>
          <button @click="confirmDelete" class="btn-delete">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {getContractInfo} from "@/api/contract.js";

// 响应式数据
const searchForm = ref({
  contractNo: '',
  ownerName: '',
  phone: '',
  houseCode: '',
  expiryOption: '',
  endDate: '',
  contractStatus: ''
})

//获取合同数据
const contracts = ref([])
const loading = ref(false)
const filteredContracts = ref([])// 初始化已过滤的合同列表为所有合同
const fetchContracts = async () => {
  loading.value = true
  try {
    const response = await getContractInfo()
    contracts.value = response.data || []
    filteredContracts.value = contracts.value
    updatePagination()
  }catch ( error){
    console.error( "获取合同数据失败",error)
  }finally {
    loading.value = false
  }
}

// 计算属性：将月份转换为年份显示
const formatContractTerm = (months) => {
  if (!months) return ''
  const years = months / 12
  if(years === 0.5){
    return '半年'
  }else{
    return Number.isInteger(years) ? `${years}年` : `${months}个月`
  }
}


const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  totalPages: 1,
  total: 0
})

const showModal = ref(false)
const modalType = ref('add') // 'add', 'edit', 'view'
const currentContract = ref({})// 当前正在处理的合同
const gotoPage = ref('')
const fileInput = ref(null)

// 新增的状态变量
const operationMode = ref('add') // 'add', 'edit', 'delete'
const selectedContracts = ref([])
const showDeleteConfirm = ref(false)
const deleteType = ref('single') // 'single', 'batch'
const deleteTarget = ref({})

// 计算属性
const modalTitle = computed(() => {
  switch (modalType.value) {
    case 'add': return '新增合同'
    case 'edit': return '编辑合同'
    case 'view': return '查看合同详情'
    default: return ''
  }
})

const paginatedContracts = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredContracts.value.slice(start, end)
})

const visiblePages = computed(() => {
  const current = pagination.value.currentPage
  const total = pagination.value.totalPages
  const pages = []

  for (let i = Math.max(1, current - 2); i <= Math.min(total, current + 2); i++) {
    pages.push(i)
  }

  return pages
})

const isAllSelected = computed(() => {
  return paginatedContracts.value.length > 0 &&
      paginatedContracts.value.every(contract => selectedContracts.value.includes(contract.contract_id))
})

// 方法
const updatePagination = () => {
  pagination.value.total = filteredContracts.value.length
  pagination.value.totalPages = Math.ceil(filteredContracts.value.length / pagination.value.pageSize)
  if (pagination.value.currentPage > pagination.value.totalPages) {
    pagination.value.currentPage = 1
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return dateString.split('T')[0]
}

// 格式化合同状态显示文本和样式
const formatContractStatus = (status) => {
  const statusMap = {
    0: { text: '待生效', class: 'status-pending' },
    1: { text: '生效', class: 'status-active' },
    2: { text: '过期', class: 'status-expired' },
    3: { text: '终止', class: 'status-terminated' }
  }
  return statusMap[status] || { text: '未知', class: 'status-unknown' }
}


const handleSearch = () => {
  filteredContracts.value = contracts.value.filter(contract => {
    // 基本字段匹配
    const basicMatch = (
      (!searchForm.value.contractNo || contract.contract_code.includes(searchForm.value.contractNo)) &&
      (!searchForm.value.ownerName || contract.tenant_name.includes(searchForm.value.ownerName)) &&
      (!searchForm.value.phone || contract.tenant_phone.includes(searchForm.value.phone)) &&
      (!searchForm.value.houseCode || contract.house_code.includes(searchForm.value.houseCode))&&
      (searchForm.value.contractStatus === '' || contract.contract_status === parseInt(searchForm.value.contractStatus))
    )

    // 到期日期匹配
    let dateMatch = true
    if (searchForm.value.expiryOption) {
      const contractEndDate = new Date(contract.expiry_date)
      const today = new Date()

      switch (searchForm.value.expiryOption) {
        case 'custom':
          if (searchForm.value.endDate) {
            dateMatch = contractEndDate <= new Date(searchForm.value.endDate)
          }
          break
        case '3months':
          const threeMonthsLater = new Date()
          threeMonthsLater.setMonth(today.getMonth() + 3)
          dateMatch = contractEndDate <= threeMonthsLater && contractEndDate >= today
          break
        case '1month':
          const oneMonthLater = new Date()
          oneMonthLater.setMonth(today.getMonth() + 1)
          dateMatch = contractEndDate <= oneMonthLater && contractEndDate >= today
          break
        case '7days':
          const sevenDaysLater = new Date()
          sevenDaysLater.setDate(today.getDate() + 7)
          dateMatch = contractEndDate <= sevenDaysLater && contractEndDate >= today
          break
      }
    }

    return basicMatch && dateMatch
  })
  pagination.value.currentPage = 1
  selectedContracts.value = []
  updatePagination()
}

const handleReset = () => {
  searchForm.value = {
    contractNo: '',
    ownerName: '',
    phone: '',
    houseCode: '',
    expiryOption: '',
    endDate: '',
    contractStatus: ''
  }
  filteredContracts.value = [...contracts.value]
  pagination.value.currentPage = 1
  selectedContracts.value = []
  updatePagination()
}

const handleAdd = () => {
  operationMode.value = 'add'
  selectedContracts.value = []
  modalType.value = 'add'
  currentContract.value = {
    contract_id: Date.now(),
    contract_code: '',
    tenant_name: '',
    tenant_phone: '',
    house_code: '',
    contract_term: '',
    effective_date: new Date().toISOString().split('T')[0],
    expiry_date: new Date(Date.now() + 365*24*60*60*1000).toISOString().split('T')[0],
    contract_status: 1,
    contract_scanner_url: null,
    create_by: '当前用户',
    create_time: new Date().toISOString(),
    update_by: '当前用户',
    update_time: new Date().toISOString(),
    rent: '',
    deposit: '',
    payment_due_date: '',
    payment_cycle: '',
    initial_water_meter: '',
    initial_electricity_meter: '',
    initial_gas_meter: '',
    remark: ''
  }
  showModal.value = true
}

const handleModeChange = (mode) => {
  operationMode.value = mode
  selectedContracts.value = []
}

const handleEdit = (contract) => {
  modalType.value = 'edit'
  currentContract.value = { ...contract }
  showModal.value = true
}

const handleView = (contract) => {
  modalType.value = 'view'
  currentContract.value = { ...contract }
  showModal.value = true
}

const handleSingleDelete = (contract) => {
  deleteType.value = 'single'
  deleteTarget.value = contract
  showDeleteConfirm.value = true
}

const handleBatchDelete = () => {
  if (selectedContracts.value.length === 0) return
  deleteType.value = 'batch'
  showDeleteConfirm.value = true
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedContracts.value = paginatedContracts.value.map(contract => contract.contract_id)
  } else {
    selectedContracts.value = []
  }
}

const confirmDelete = () => {
  if (deleteType.value === 'single') {
    // 单个删除
    const contractId = deleteTarget.value.contract_id
    contracts.value = contracts.value.filter(contract => contract.contract_id !== contractId)
    filteredContracts.value = filteredContracts.value.filter(contract => contract.contract_id !== contractId)
  } else {
    // 批量删除
    contracts.value = contracts.value.filter(contract => !selectedContracts.value.includes(contract.contract_id))
    filteredContracts.value = filteredContracts.value.filter(contract => !selectedContracts.value.includes(contract.contract_id))
    selectedContracts.value = []
  }

  updatePagination()
  showDeleteConfirm.value = false
  deleteTarget.value = {}
}

const cancelDelete = () => {
  showDeleteConfirm.value = false
  deleteTarget.value = {}
}

const handleSave = () => {
  if (modalType.value === 'add') {
    contracts.value.push({...currentContract.value})
    filteredContracts.value.push({...currentContract.value})
  } else if (modalType.value === 'edit') {
    const index = contracts.value.findIndex(contract => contract.contract_id === currentContract.value.contract_id)
    if (index !== -1) {
      contracts.value[index] = {...currentContract.value}
    }
    const filteredIndex = filteredContracts.value.findIndex(contract => contract.contract_id === currentContract.value.contract_id)
    if (filteredIndex !== -1) {
      filteredContracts.value[filteredIndex] = {...currentContract.value}
    }
  }
  updatePagination()
  closeModal()
}

const closeModal = () => {
  showModal.value = false
  currentContract.value = {}
}

const goToPage = (page) => {
  pagination.value.currentPage = page
  selectedContracts.value = []
}

const goToPrevPage = () => {
  if (pagination.value.currentPage > 1) {
    pagination.value.currentPage--
    selectedContracts.value = []
  }
}

const goToNextPage = () => {
  if (pagination.value.currentPage < pagination.value.totalPages) {
    pagination.value.currentPage++
    selectedContracts.value = []
  }
}

const handleGotoPage = () => {
  const page = parseInt(gotoPage.value)
  if (page >= 1 && page <= pagination.value.totalPages) {
    pagination.value.currentPage = page
    gotoPage.value = ''
    selectedContracts.value = []
  }
}

// 文件处理相关方法
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 模拟文件上传过程
    const reader = new FileReader()
    reader.onload = (e) => {
      currentContract.value.contract_scanner_url = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

const removeFile = () => {
  currentContract.value.contract_scanner_url = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const getFileName = (url) => {
  if (!url) return ''
  return url.substring(url.lastIndexOf('/') + 1)
}

const isImageFile = (url) => {
  if (!url) return false
  return /\.(jpeg|jpg|png|gif|bmp)$/i.test(url)
}

const isPdfFile = (url) => {
  if (!url) return false
  return /\.pdf$/i.test(url)
}

const getFileExtension = (url) => {
  if (!url) return 'FILE'
  const match = url.match(/\.([^.]+)$/i)
  return match ? match[1].toUpperCase() : 'FILE'
}

// 下载文件
const downloadFile = (url) => {
  const link = document.createElement('a')
  link.href = url
  link.download = getFileName(url) || 'contract-file'
  link.click()
}

// 生命周期
onMounted(() => {
  fetchContracts()
})
</script>

<style scoped>
/* 基础布局样式 */
.personnel-management {
  width: 100%;
  background-color: rgba(255, 255, 255, 1);
  padding: 30px 30px;
  box-sizing: border-box;
  overflow: hidden;
  border-radius: 0 15px 15px 15px;
}

/* 页面标题 */
.page-title {
  color: rgba(231, 59, 69, 1);
  font-size: 18px;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  margin: 0 0 20px 0;
  line-height: 25px;
}

/* 搜索筛选区域 */
.search-filters {
  margin-bottom: 6px;
}

.search-item {
  display: block;
  margin-bottom: 5px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  width: 1527px;
  height: 32px;
}

/* 统一的输入框和选择框样式 */
.input-field, .select-field {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  width: 180px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(153, 153, 153, 1);
  box-sizing: border-box;
  line-height: 20px;
}

.input-field:focus, .select-field:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
  color: rgba(0, 0, 0, 1);
}

.input-field::placeholder {
  color: rgba(153, 153, 153, 1);
}

/* 统一的按钮样式 */
.btn-primary {
  background-color: rgba(231, 59, 69, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-secondary {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: 1px solid rgba(151, 151, 151, 1);
  color: rgba(135, 136, 138, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
}

.btn-add {
  background-color: rgba(252, 235, 236, 1);
  border-radius: 19px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(231, 59, 69, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-add:hover {
  background-color: rgba(248, 220, 222, 1);
}

.btn-batch-delete {
  background-color: rgba(255, 77, 79, 1);
  border-radius: 19px;
  height: 32px;
  padding: 0 16px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-batch-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}

.btn-icon {
  width: 13px;
  height: 13px;
}

.btn-download {
  background-color: rgba(231, 59, 69, 1);
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  margin-top: 10px;
}

.remove-file-btn {
  background: none;
  border: 1px solid #ccc;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-weight: bold;
  color: #999;
}

/* 分割线 */
.divider {
  width: 1533px;
  height: 1px;
  background-color: rgba(237, 239, 244, 1);
  margin: 50px 0 0 0;
}

/* 操作按钮组样式 */
.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin: 20px 0;
}

/* 表格样式 */
.table-container {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
  width: 100%;
  height: 610px;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.table-header {
  background-color: rgba(249, 248, 252, 1);
  height: 60px;
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-header th {
  color: rgba(0, 0, 0, 1);
  font-size: 16px;
  font-weight: normal;
  text-align: left;
  padding: 13px 21px;
  line-height: 20px;
}

.table-row {
  background-color: rgba(255, 255, 255, 1);
  height: 55px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-row td {
  color: rgba(102, 102, 102, 1);
  font-size: 16px;
  font-weight: normal;
  padding: 10px 21px;
  line-height: 20px;
  white-space: nowrap;
}

/* 合同状态样式 */
/* 在原有的 .status-badge 样式后添加以下样式 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: rgba(24, 144, 255, 0.2);
  color: rgba(24, 144, 255, 1);
}

.status-active {
  background-color: rgba(45, 183, 120, 0.2);
  color: rgba(45, 183, 120, 1);
}

.status-expired {
  background-color: rgba(153, 153, 153, 0.2);
  color: rgba(153, 153, 153, 1);
}

.status-terminated {
  background-color: rgba(255, 77, 79, 0.2);
  color: rgba(255, 77, 79, 1);
}

.status-unknown {
  background-color: rgba(153, 153, 153, 0.2);
  color: rgba(153, 153, 153, 1);
}

/* 复选框样式 */
.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 43px;
  align-items: center;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn img {
  width: 13px;
  height: 13px;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.pagination-info {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
}

.pagination-btn {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  min-width: 32px;
  height: 32px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-btn:hover:not(:disabled) {
  background-color: rgba(249, 248, 252, 1);
}

.pagination-btn.active {
  background-color: rgba(231, 59, 69, 1);
  color: white;
  border-color: rgba(231, 59, 69, 1);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-goto {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
  margin-left: 20px;
}

.goto-input {
  width: 50px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px;
  font-size: 14px;
  text-align: center;
  line-height: 20px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.delete-confirm-modal {
  width: 400px;
  max-height: none;
  overflow-y: visible;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(237, 239, 244, 1);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: rgba(231, 59, 69, 1);
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: rgba(102, 102, 102, 1);
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: rgba(231, 59, 69, 1);
}

.modal-body {
  padding: 20px;
}

.modal-body p {
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  line-height: 1.5;
  margin: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-item.full-width {
  grid-column: span 2;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  font-weight: 500;
  line-height: 20px;
}

.form-input, .form-textarea {
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  line-height: 20px;
  box-sizing: border-box;
}

.form-textarea {
  height: auto;
  min-height: 80px;
  resize: vertical;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
}

.form-input:disabled, .form-textarea:disabled {
  background-color: rgba(249, 248, 252, 1);
  color: rgba(153, 153, 153, 1);
  cursor: not-allowed;
}

.file-preview {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.file-container {
  width: 100%;
  margin-top: 10px;
}

.contract-file-preview {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #ddd;
  margin-top: 10px;
}

.file-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 200px;
  background-color: #f5f5f5;
  border: 1px dashed #ddd;
  margin-top: 10px;
}

.file-icon span {
  font-size: 48px;
  margin-bottom: 10px;
}

.no-file {
  color: #999;
  font-style: italic;
  margin-top: 10px;
}

.file-upload-area {
  border: 2px dashed #ccc;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
  margin-top: 10px;
}

.file-upload-area:hover {
  border-color: rgba(231, 59, 69, 1);
}

.upload-placeholder {
  color: #999;
  font-size: 14px;
}

.file-input {
  display: none;
}

.uploaded-file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-top: 10px;
}

.file-preview-container {
  margin-top: 10px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid rgba(237, 239, 244, 1);
}

.btn-cancel {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  line-height: 20px;
}

.btn-save, .btn-delete {
  background-color: rgba(231, 59, 69, 1);
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  line-height: 20px;
}

.btn-delete {
  background-color: rgba(255, 77, 79, 1);
}

.btn-cancel:hover {
  background-color: rgba(249, 248, 252, 1);
}

.btn-save:hover {
  background-color: rgba(207, 53, 63, 1);
}

.btn-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}
</style>
